﻿namespace MapleRock.P2PEmulator.Core
{
  using System.Diagnostics;

  public static class LatencyTable
  {
    private static double[,] tableData = new double[,] 
    { 
      { 71, 42 },     { 118, 102 },   { 252, 24 },    { 267, 86 },    { 326, 77 },    { 407, 58 }, 
      { 522, 233 },   { 565, 35 },    { 603, 96 },    { 649, 65 },    { 713, 193 },   { 750, 122 }, 
      { 791, 50 },    { 1072, 37 },   { 1080, 75 },   { 1144, 72 },   { 1184, 47 },   { 1395, 211 }, 
      { 1455, 99 },   { 1563, 68 },   { 1568, 131 },  { 1685, 176 },  { 2263, 240 },  { 2336, 121 }, 
    };

    public static double GetLatency(double distance)
    {
      Debug.Assert(distance > 0, "distance > 0");

      var aIndex = -1;
      var bIndex = -1;

      if (distance <= tableData[0, 0])
      {
        aIndex = 0;
        bIndex = 1;
      }

      var maxIndex = (tableData.GetLength(0) - 1);
      if (distance >= tableData[maxIndex, 0])
      {
        aIndex = maxIndex - 1;
        bIndex = maxIndex;
      }

      for (var i = 1; i <= maxIndex; ++i)
      {
        if (tableData[i, 0] > distance)
        {
          aIndex = (i - 1);
          bIndex = i;
          break;
        }
      }

      Debug.Assert(aIndex != -1, "aIndex != -1");
      Debug.Assert(bIndex != -1, "bIndex != -1");

      var aDist = tableData[aIndex, 0];
      var bDist = tableData[bIndex, 0];
      var k = (distance - aDist) / (bDist - aDist);

      var aLatency = tableData[aIndex, 1];
      var bLatency = tableData[bIndex, 1];

      var result = aLatency + ((bLatency - aLatency) * k);

      return result;
    }
  }
}
